#!/usr/bin/env bash
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
# Function :CentOS7.X  批量（drds服务器组内） 执行 命令
# Platform :RedHatEL7.x Based Platform
# Version  :1.02
# Date     :2022-05-04
# Author   :mugoLH
# Contact  :houxiaoshuai@baidu.com & hxsaj@126.com
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
#  变量列表 List of common variables
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
#  获取主机名列的源文件
DEFAULT_HOST_FILE=/etc/hosts
#  默认主机组关键字（可以设为空）
DEFAULT_HOST_KEY=""
#  主机组关键字（默认留空）
HOST_KEY=""


#  函数列表 Function list
# ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
info_p(){    printf "\e[1;35;40m%-8s %-20s %-24s %-2s %-2s\e[0m\n" "$(date '+%H:%M:%S')" "${1}" "${2}" "${3}" "${4}" >&1 ;}
error_p(){ printf "\e[1;35;40m%-8s\e[0m %-12s %-1s\n\e[0m"      "$(date '+%H:%M:%S')" "${1}" "${2}"  >&1 ;}


help_f(){
    echo -e "说明：\n    pcp [ 本地文件/目录 ] [ 远程服务器文件名/目录 ] 实现批量复制本机文件或目录到远程主机"
    echo -e "\n示例：\n"
    echo -e "  pcp ~/.ssh /home/work/                   :从本机复制家目录下的.ssh目录到默认所有服务器的/home/work下"
    echo -e "  pcp -g zookeeper ./zk/zoo.cfg /home/     :从本机复制./zk/zoo.cfg文件到到zookeeper服务器组的/home下"
    echo -e "  pcp -g zookeeper -f ./host.list ./zoo.cfg /home/  :本机复制复制./zk/zoo.cfg到./host.list主机清单文件中指定 zookeeper 关键字的服务器/home下"
    echo -e "\n可用的选项如下（也可不加选项默认执行所有默认主机）："
    echo -e "  -f or --file  指定IP和主机名文件，类似/etc/hosts"
    echo -e "  -g or --group 指定服务器主机名关键字，也就是主机组，指定在指定的主机组上执行命令"
    echo -e "\n主机名清单类似如下：
#  配置列表 Configuration list
#  ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
#  IP地址         |主机名       | 部署的组件(zk,xdb,dts,smartdba)
#  ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
192.168.123.29    drdsmp01       zookeeper,xdb
192.168.123.111   drdsmp02       zookeeper,xdb
192.168.123.79    drdsnode01     zookeeper
192.168.123.106   drdsnode02
192.168.123.215   drdsbaknode01
"
}
#  IP检查合法性
check_ip() {
    IP=$1
    if [[ $IP =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
        FIELD1=$(echo $IP|cut -d. -f1)
        FIELD2=$(echo $IP|cut -d. -f2)
        FIELD3=$(echo $IP|cut -d. -f3)
        FIELD4=$(echo $IP|cut -d. -f4)
        if [ $FIELD1 -le 255 -a $FIELD2 -le 255 -a $FIELD3 -le 255 -a $FIELD4 -le 255 ]; then
            echo "ok"
        else
            echo "no"
        fi
    else
        echo "error"
    fi
}

ctl_ops(){
    if [ $# -eq 2 ];then
        #  如果未指定主机组，则获取主机文件中所有主机
        if [[ -z ${HOST_KEY} ]];then
            #  获取主机 IP 列表
            IPs=($(grep -Ev "localhost|^#|$(uname -n)" ${HOST_FILE} | awk '{print$1}' | sort | uniq ))
            #  指定主机组，则获取主机文件中指定的主机组 IP 列表
        elif [[ -n ${HOST_KEY} ]]; then
            IPs=($(grep -Ev "localhost|^#|$(uname -n)" ${HOST_FILE} | grep ${HOST_KEY}| awk '{print$1}' | sort | uniq ))
        fi
        Local_Ips=($(ifconfig | grep -w inet | awk '{print$2}'))

        for i in ${Local_Ips[@]};do
            if [ $(check_ip ${i}) == "ok" ];then
                c=$(echo ${IPs[*]} | sed 's/\<'$i'\>//'); 
            fi
            unset IPs
            IPs=${c[@]}
        done

        #  遍历主机组 IP 执行命令
        for i in ${IPs[@]};do
            if [ $(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print NF}') -ge 6 ];then
                Host_Name=$(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print$2}' | sort | uniq)
                Host_User=$(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print$5}' | sort | uniq)
                Host_Port=$(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print$6}' | sort | uniq)
                info_p "从本机复制 ${1} ----> " "${Host_Name}[ IP:${i} ]:${2}"

                if [ $(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print NF}') -eq 6 ];then
                    scp -pr -P ${Host_Port} ${1} ${Host_User}@${i}:${2}
                    echo ""
                elif [ $(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print NF}') -eq 7 ];then
                    Host_Pass=$(egrep -v "^$|^#" ${HOST_FILE} | grep -w ${i} | awk '{print$7}')
                    sshpass -p "${Host_Pass}" scp -pr -P ${Host_Port} ${1} ${Host_User}@${i}:${2}
                    echo ""
                fi
            else
                Host_Name=$(grep -Ev "^#" ${HOST_FILE} | grep -w ${i} | awk '{print$2}' | sort | uniq)
                info_p "从本机复制 ${1} ----> " "${Host_Name}[ IP:${i} ]:${2}"
                scp -pr ${1} ${i}:${2}
                echo ""
            fi
        done
    else
        break 0
    fi
}
# 如果参数为空，则退出
if [ $# -eq 0 ];then
    exit
elif [[ $# -eq 1 ]]; then
    help_f
else
    #  获取主机组关键字
    while [ -n "$1" ]; do
        case $1 in
            -g | --group)
                HOST_KEY="${2}"
                shift 2
                ;;
            -f | --file )
                HOST_FILE="${2}"
                shift 2
                ;;
            -h | --help )
                help_f
                exit
                ;;
            *)
                break
                ;;
        esac
    done
    #  循环远程执行命令
    #  指定主机清单文件和指定主机关键字
    [[ ! -f ${HOST_FILE} ]] && HOST_FILE=${DEFAULT_HOST_FILE}
    #  指定关键字
    [[ -z ${HOST_KEY} ]]    && HOST_KEY=${DEFAULT_HOST_KEY}
    #  遍历主机执行命令
    if [ ! -z ${1} ] && [ ! -z ${2} ];then
        ctl_ops "${1}" "${2}"
    else
        error_p  "[ NOTICE ]:" "源文件/源目录或目的文件/目录缺失，请检查！"
    fi
fi